import { NotifyModel } from "@/api/notify/notifyModel";
import main from "@/main";
import {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
} from "@/settings/mutation-types"
import { RootState, State } from "vue"
import { ActionContext } from "vuex";



const socket = {
  state: () => ({
    socket: {
      isConnected: false,
      notifyMessage: [],
      // 重新连接错误
      reconnectError: false,
      // 心跳消息发送时间
      heartBeatInterval: 50000,
      // 心跳定时器
      heartBeatTimer: 0,

    }
  }),
  mutations: {
    // 连接打开
    async [SOCKET_ONOPEN](state: State, event: any) {
      main.config.globalProperties.$socket = event.currentTarget;
      state.socket.isConnected = true
      console.log(state)
      // main.config.globalProperties.$socket.sendObj();
      // 连接成功时启动定时发送心跳消息，避免被服务器断开连接
      state.socket.heartBeatTimer = setInterval(() => {
        const message = "心跳消息";
        state.socket.isConnected &&
          main.config.globalProperties.$socket.sendObj({
            code: 200,
            msg: message
          });
      }, state.socket.heartBeatInterval);
    },
    // 连接关闭
    [SOCKET_ONCLOSE](state: State, event: any) {
      state.socket.isConnected = false
      // 连接关闭时停掉心跳消息
      clearInterval(state.socket.heartBeatTimer);
      state.socket.heartBeatTimer = 0;
      console.log("连接已断开: " + new Date());
      console.log(event);
    },
    // 发生错误
    [SOCKET_ONERROR](state: State, event: any) {
      console.error(state, event)
    },
    // 收到服务端发送的消息
    // default handler called for all methods
    [SOCKET_ONMESSAGE](state: State, message: any) {
      console.log(message)
      if (message.msg !== '心跳消息') {
        state.socket.notifyMessage.push(message)
      }
    },
    // 自动重连
    // mutations for reconnect methods
    [SOCKET_RECONNECT](state: State, count: any) {
      console.info("消息系统重连中...", state, count);
    },

    [SOCKET_RECONNECT_ERROR](state: State) {
      state.socket.reconnectError = true;
    },
    ADD_NOTIFY_MESSAGE(state: State, message: NotifyModel) {
      state.socket.notifyMessage = state.socket.notifyMessage.concat(message)
    }
  },
  actions: {
    addNotifyMessage: ({ commit }: ActionContext<State, RootState>, message: NotifyModel) => {
      commit('ADD_NOTIFY_MESSAGE', message)
    }
  },
  getters: {
    getSocket(state: State) {
      return state.socket
    }
  }
}
export default socket